package com.hfi.security.app.social;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @author ChangLiang
 * @date 2019/9/3
 */
@Component
public class AppSignUpUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UsersConnectionRepository usersConnectionRepository;

    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    /**
     * 将第三方社交账号用户信息插入到关联表中
     * @param userId
     * @param request
     */
    public void doPostSignUp(String userId, WebRequest request) {
        String key = getKey(request);
        if (!redisTemplate.hasKey(key)) {
            throw new AppSignUpException("无法找到缓存的用户社交账号信息");
        }
        ConnectionData connectionData = (ConnectionData) redisTemplate.opsForValue().get(key);
        // 把ConnectionData转换为Connection
        Connection<?> connection =
                connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId()).createConnection(connectionData);
        usersConnectionRepository.createConnectionRepository(userId).addConnection(connection);
        // 之后在redisTemplate中删除掉
        redisTemplate.delete(key);
    }

    /**
     * 将社交登录的用户信息存储到外部存储redis中
     * @param request
     * @param connectionData
     */
    public void saveConnectionDate(WebRequest request, ConnectionData connectionData) {
        redisTemplate.opsForValue().set(getKey(request),connectionData,10, TimeUnit.MINUTES);
    }

    private String getKey(WebRequest request) {
        String deviceId = request.getHeader("deviceId");
        if (StringUtils.isBlank(deviceId)) {
            throw new AppSignUpException("请在请求头中携带deviceId参数");
        }
        return "hfi:security:social:connect:" + deviceId;
    }
}
